<template>
  <div class="app">
    <h1>学生信息管理系统</h1>
    
    <div v-if="showForm">
      <StudentForm 
        :student="currentStudent" 
        @submit="handleSubmit" 
        @cancel="showForm = false" 
      />
    </div>
    
    <div v-else>
      <button @click="showAddForm">添加学生</button>
    </div>
    
    <StudentList 
      :students="students" 
      @edit="editStudent" 
      @delete="deleteStudent" 
    />
  </div>
</template>

<script>
import { ref } from 'vue';
import StudentList from './components/StudentList.vue';
import StudentForm from './components/StudentForm.vue';
import studentsData from './data/students';

export default {
  components: {
    StudentList,
    StudentForm
  },
  setup() {
    const students = ref([...studentsData]);
    const showForm = ref(false);
    const currentStudent = ref(null);

    const showAddForm = () => {
      currentStudent.value = null;
      showForm.value = true;
    };

    const editStudent = (student) => {
      currentStudent.value = student;
      showForm.value = true;
    };

    const deleteStudent = (id) => {
      if (confirm('确定要删除该学生吗？')) {
        students.value = students.value.filter(s => s.id !== id);
      }
    };

    const handleSubmit = (studentData) => {
      if (studentData.id) {
        // 更新学生
        const index = students.value.findIndex(s => s.id === studentData.id);
        if (index !== -1) {
          students.value[index] = studentData;
        }
      } else {
        // 添加新学生
        const newId = Math.max(...students.value.map(s => s.id), 0) + 1;
        students.value.push({
          ...studentData,
          id: newId
        });
      }
      showForm.value = false;
    };

    return {
      students,
      showForm,
      currentStudent,
      showAddForm,
      editStudent,
      deleteStudent,
      handleSubmit
    };
  }
}
</script>

<style>
.app {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}
</style>